package commands.gameCommand
{
	import commands.ICommand;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	
	public class Piece extends Sprite
	{
		private var _background:Sprite;
		private var _label:TextField;
		private var _data:PieceData;
		private var _command:ICommand;
		
		public function Piece()
		{
			this.addEventListener(MouseEvent.MOUSE_OVER,onMouseOver);
			this.addEventListener(MouseEvent.MOUSE_OUT,onMouseOut);
			this.addEventListener(MouseEvent.CLICK,onClick);
			
			_background = new Sprite;
			addChild(_background);
			
			_label = new TextField();
			addChild(_label);
			_label.selectable = false;
			_label.autoSize = TextFieldAutoSize.LEFT;
		}

		public function get data():PieceData
		{
			return _data;
		}

		public function set data(value:PieceData):void
		{
			_data = value;
			_data.addEventListener(Event.CHANGE,draw);
			
			_command = CommandFactory.getGamePlayCommand(_data);
			draw();
			
		}
		private function onMouseOver(event:MouseEvent):void{
			_background.alpha = 0.1;
		}
		private function onMouseOut(event:MouseEvent):void{
			_background.alpha = 1;	
		}
		private function onClick(event:MouseEvent):void{
			_command.execute();
		}
		public function draw(event:Event = null):void{
			var color:uint = _data.owner.color;
			var newX:Number;
			var newY:Number;
			var angle:Number = -Math.PI/6;
			var angleDelta:Number = Math.PI/3;
			_background.graphics.clear();
			_background.graphics.lineStyle(0,0,0);
			_background.graphics.beginFill(color,1);
			newX = Math.cos(angle) * _data.radius;
			newY = Math.sin(angle) * _data.radius;
			_background.graphics.moveTo(newX,newY);
			for(var i:uint = 0;i < 6;i++){
				angle += angleDelta;
				newX = Math.cos(angle) * _data.radius;
				newY = Math.sin(angle) * _data.radius;
				_background.graphics.lineTo(newX,newY);
			}
			_background.graphics.endFill();
			if(_data.row != -1){
				x = (_data.row%2 == 0 ? 0 : _data.radius) + _data.column * _data.radius * 2;
				y = _data.column * _data.radius * 2;
			}
			
			_label.text = String(_data.count);
			_label.x = -_label.width/2;
			_label.y = -_label.height/2;
			
		}

	}
}






